import Vue from 'vue';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import modelUser from '../models/user';
import store from '../store';

Vue.use(VueRouter);

const routes = [
    /**
     * 主页
     */
    {
        path: '/',
        component: () => import('../views/home/Home'),
        children: [
            // 首页
            {
                path: '',
                name: 'main-home',
                component: () => import('../views/home/Index'),
                meta: {
                    auth: false,
                    role: 'all'
                }
            },
            // 公告
            {
                path: 'announcement',
                name: 'main-announcement',
                component: () => import('../views/home/Announcement'),
                meta: {
                    auth: false,
                    role: 'all'
                }
            },
            /*{
                path: 'announcement-detail/:id',
                name: 'announcement-detail',
                component: () => import('../views/home/AnnouncementDetail'),
                meta: {
                    auth: true
                }
            },*/
            // 活动
            {
                path: 'activity',
                name: 'main-activity',
                component: () => import('../views/home/Activity'),
                meta: {
                    auth: false,
                    role: 'all'
                }
            },
            /*{
                path: 'activity-detail/:id',
                name: 'main-activity-detail',
                component: () => import('../views/home/ActivityDetail'),
                meta: {
                    auth: true
                }
            },*/
            {
                path: 'detail/:type/:id',
                name: 'main-detail',
                component: () => import('../views/home/Detail'),
                meta: {
                    auth: false,
                    role: 'all'
                }
            },
            // 留言
            {
                path: 'comment',
                name: 'main-comment',
                component: () => import('../views/home/Comment'),
                meta: {
                    auth: true,
                    role: 'all'
                }
            },
            // 服务
            {
                path: 'service',
                name: 'main-service',
                component: () => import('../views/home/Service'),
                meta: {
                    auth: true,
                    role: 'all'
                }
            },
            // 资料
            {
                path: 'profile',
                name: 'main-profile',
                component: () => import('../views/home/Profile'),
                meta: {
                    auth: true,
                    role: 'all'
                }
            },
        ]
    },


    /**
     * 登录
     */
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/Login'),
        meta: {
            auth: false,
            role: 'all'
        }
    },


    /**
     * 管理员
     */
    {
        path: '/admin',
        component: () => import('../views/admin/Home'),
        meta: {
            auth: true,
            role: ['1', '2']
        },
        children: [
            /**
             * Dashboard
             */
            {
                path: '',
                name: 'dash',
                component: () => import('../views/admin/Dash'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },


            /**
             * 基础服务
             */
            // 社区公告
            {
                path: 'announcement',
                name: "announcement",
                component: () => import('../views/admin/basic/Announcement'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                },
            },
            {
                path: 'announcement-editor/:id?',
                name: 'announcement-editor',
                component: () => import('../views/admin/basic/AnnouncementEditor'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            // 娱乐活动
            {
                path: 'activity',
                name: "activity",
                component: () => import('../views/admin/basic/Activity'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            {
                path: 'activity-editor/:id?',
                name: 'activity-editor',
                component: () => import('../views/admin/basic/ActivityEditor'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            // 居民留言
            {
                path: 'comment',
                name: "comment",
                component: () => import('../views/admin/basic/Comment'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },


            /**
             * 人员管理
             */
            // 居民管理
            {
                path: 'resident',
                name: "resident",
                component: () => import('../views/admin/person/Resident'),
                meta: {
                    auth: true,
                    role: ['2']
                }
            },
            // 工作人员
            {
                path: 'staff',
                name: "staff",
                component: () => import('../views/admin/person/Staff'),
                meta: {
                    auth: true,
                    role: ['2']
                }
            },
            // 编辑
            {
                path: 'user-editor/:type/:id?',
                name: "user-editor",
                component: () => import('../views/admin/person/UserEditor'),
                meta: {
                    auth: true,
                    role: ['2']
                }
            },


            /**
             * 服务管理
             */
            // 随访记录
            {
                path: 'visit-record',
                name: "visit-record",
                component: () => import('../views/admin/service/VisitRecord'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            {
                path: 'visit-record-editor/:id?',
                name: "visit-record-editor",
                component: () => import('../views/admin/service/VisitRecordEditor'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            // 就诊记录
            {
                path: 'medical-service',
                name: "medical-service",
                component: () => import('../views/admin/service/MedicalService'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            {
                path: 'medical-service-editor/:id?',
                name: "medical-service-editor",
                component: () => import('../views/admin/service/MedicalServiceEditor'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            },
            // 工作区域
            {
                path: 'work-place',
                name: "work-place",
                component: () => import('../views/admin/service/WorkPlace'),
                meta: {
                    auth: true,
                    role: ['2']
                }
            },
            // 疾病类型
            {
                path: 'treatment-type',
                name: "treatment-type",
                component: () => import('../views/admin/service/TreatmentType'),
                meta: {
                    auth: true,
                    role: ['1', '2']
                }
            }
        ]
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    // base:'/dist/',
    routes
})

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

// 注册全局守卫
// 在访问路由之前进行拦截
router.beforeEach((to, from, next) => {
    // 获取 token，登录的标识
    const token = Cookies.get("token");
    // 有token，直接登录
    if (token) {
        modelUser.loginGetUserData(token)
            .then(() => {
                nextVerify();
            })
            .catch(() => {
                toLogin();
            });
    }
    else toLogin();

    // 登录
    function toLogin() {
        // 判断是否需要权限
        if (to.meta.auth && !modelUser.isLogin()) {
            // 没有权限，导向登录页
            next({
                path: "/login",
                // 记录原本想访问的路由
                query: {redirect: to.fullPath}
            });
        }
        else nextVerify();
    }

    // next 验证角色能否进路由
    function nextVerify() {
        // 都可以进
        if (to.meta.role == 'all') next();
        else {
            // 没登录，不让进
            if (!modelUser.isLogin()) {
                next({path: "/"});
                console.log('权限不足1！');
            }
            // 验证权限
            else {
                const userRole = store.state.userData.role;
                // 可以进
                if (contains(to.meta.role, userRole)) next();
                else {
                    next({path: "/"});
                    console.log('权限不足2！');
                }
            }
        }
    }


    /**
     * arr包含b?
     *
     * @param arr
     * @param b
     * @return {boolean}
     */
    function contains(arr, b) {
        let is = false;
        arr.forEach((item) => {
            if (!is && item == b) is = true;
        });
        return is;
    }
})

export default router;
